<!-- 创单搜索目的地 -->
<template>
	<view class="container">
		<!-- 选择地区和输入地址 -->
		<view class="head">
			<view class="left">
				<!-- 级联选择器 -->
				<uni-data-picker
					:localdata="areaTree"
					v-slot:default="{data, error, options}"
					popup-title="请选择所在地区"
					@change="onCityChange"
				>
					<view v-if="data.length">
						<text>{{ data[data.length - 1].text }}</text>
						<uni-icons type="down" size="15" color="#666"></uni-icons>
					</view>
					<view v-else>
						<text>{{ region }}</text>
						<uni-icons type="down" size="15" color="#666"></uni-icons>
					</view>
				</uni-data-picker>
			</view>
			<view class="right">
				<input 
					type="text"
					:placeholder="enterText"
					placeholder-style="font-size:28rpx"
					style="font-size: 26rpx;"
					confirm-type="search"
					v-model="keyword"
					@confirm="handlerSearch"
				/>
			</view>
		</view>
		
		<view class="head-fill">1</view>
		
		<!-- 搜索结果 -->
		<view class="content">
			<view class="box">
				<view class="box-head">
					搜索结果
				</view>
				<view class="selectable-location-list">
					<view 
						class="selectable-location"
						v-show="selectableLocationList.length > 0"
						v-for="(item, idx) in selectableLocationList" :key="idx"
						@tap="handlerSelect(item)"
					>
						<view class="left">
							<uni-icons type="location-filled" color="#c00" size="23"></uni-icons>
						</view>
						<view class="right">
							<view class="name">
								{{ item.name }}
							</view>
							<view class="stress">
								{{ item.fullAddress }}
							</view>
						</view>
					</view>
					<!-- 未输入地址时：请输入目的位置 -->
					<view class="blank" v-show="selectableLocationList.length === 0 && !isSearching && !hasSearched">
						{{ blankText }}
					</view>
					
					<!-- 搜索中 -->
					<view class="loading-container" v-show="isSearching">
						<uni-load-more status="loading" :content-text="{contentrefresh: '搜索中...', contentnomore: '没有更多结果'}"></uni-load-more>
					</view>
					
					<!-- 无结果 -->
					<view class="blank" v-show="selectableLocationList.length === 0 && hasSearched && !isSearching">
						未找到相关地址
					</view>
					
					<view class="loading-container" v-show="pageIndex > 1 && selectableLocationList.length > 0">
						<uni-load-more 
							icon-type="circle"
							:status="loadingStatus"
							:content-text="{contentdown: '上拉加载更多', contentrefresh: '正在加载...', contentnomore: '- 到底了 -'}"
						/>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
 
 
<script setup>
import { computed, ref } from 'vue';
import areaTree from '@/utils/areaTree.js'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { calcPriceByDistance } from '@/api/order.js'

// 确保 areaTree 数据存在
const areaData = ref([])
//当前位置
const currLocation = ref({
	latitude: 0,//纬度
	longitude: 0, // 经度
	altitude: 0,// 高度
	addressInfo: {
		fullname: '', 	//地域全名
		nation: '', 	//国家
		province: '', 	//省
		city: '', 		//市
		district: '', 	//区
		street: '', 	//街道
		streetNumber: '' //门牌号
	}
})

const pageType = ref('target')
const enterText = computed(() => {
	return pageType.value === 'current' ? '请输入当前地址' : '请输入目的地址'
})
const blankText = computed(() => {
	return pageType.value === 'current' ? '请输入当前位置' : '请输入目的位置'
})

// 当前选中的地区
const region = ref('')
// 是否选择了地区
const selected = ref(false)
//搜索关键词
const keyword = ref('')
//页码
const pageIndex = ref(1)
//可选地址
const selectableLocationList = ref([])
//加载中
const loadingStatus = ref('loading')

const isSearching = ref(false)
//是否已经搜索过
const hasSearched = ref(false)

//切换城市
function onCityChange (e) {
	// selected.value = true
	// region.value = e.detail.value[e.detail.value.length - 1].value.split(':')[1]
	if (e && e.detail && e.detail.value && e.detail.value.length > 0) {
		selected.value = true
		const lastItem = e.detail.value[e.detail.value.length - 1]
		if (lastItem && lastItem.value) {
			region.value = lastItem.value.split(':')[1]
			console.log('选择了城市:', region.value)
		}
	}
}

//根据当前地区 和 关键词搜索
function handlerSearch () {
	if(!keyword.value){
		return
	}
	//重置页码
	pageIndex.value = 1
	//重置加载中
	loadingStatus.value = 'loading'
	//重置数据
	selectableLocationList.value = []
	//标记正在搜索
	isSearching.value = true
	hasSearched.value = true
	
	getNextPage().finally(() => {
		isSearching.value = false
	})
}

// 查询位置-高德
function getNextPage () {
	return new Promise((resolve, reject) => {
		// 使用原始关键词，不要添加地区前缀
		let searchKeyword = keyword.value
		
		let searchCity = ''
		if(selected.value && region.value) {
			searchCity = region.value
		} else if(region.value) {
			searchCity = region.value
		}
		// 提取城市名称（去掉区级信息）
		if(searchCity) {
			if(searchCity.includes('市')) {
				const cityMatch = searchCity.match(/(.*?市)/)
				if(cityMatch) {
					searchCity = cityMatch[1]
				}
			}
		}
		
		const amapKey = '9996b2ae4c2bd5c1caab3861243bb047'
		const url = `https://restapi.amap.com/v3/place/text?key=${amapKey}&keywords=${encodeURIComponent(searchKeyword)}&city=${region.value || ''}&page=${pageIndex.value}&offset=20&output=JSON`
		// 高德地图poi搜索
		uni.request({
			url: url,
			method: 'GET',
			keyword: searchKeyword,
			location: `${currLocation.value.longitude},${currLocation.value.latitude}`,
			page: pageIndex.value,
			pageSize: 20,
			success: (res) => {
				console.log('搜索结果', res)
				if (res.data && res.data.status === '1' && res.data.pois){ //res.pois = res.pois.length > 0
					const pois = res.data.pois.map(poi =>{
						// 构建完整地址：省+市+区+详细地址
						const fullAddress = `${poi.pname || ''}${poi.cityname || ''}${poi.adname || ''}${poi.address || ''}`
						return {
							id: poi.id,
							name: poi.name,
							location: {
								lat: parseFloat(poi.location.split(',')[1]),
								lng: parseFloat(poi.location.split(',')[0])
							},
							type: poi.type,
							pname: poi.pname,
							cityname: poi.cityname,
							adname: poi.adname,
							address: poi.address, // 详细地址（包含街道门牌号）
							fullAddress: fullAddress // 完整地址
						}
					})
					console.log('搜索内容', pois)
					
					// 拼接数据
					selectableLocationList.value = [...selectableLocationList.value, ...pois]
					// 页码+1
					pageIndex.value++
					// 更新加载状态
					loadingStatus.value = pois.length < 20 ? 'noMore' : 'more'
				} else {
					loadingStatus.value = 'noMore'
					if (pageIndex.value === 1) {
						selectableLocationList.value = []
					}
					
					// 显示错误信息
					if (res.data && res.data.info) {
						console.error('高德API错误:', res.data.info)
						uni.showToast({
							title: res.data.info || '搜索失败',
							icon: 'none'
						})
					}
				}
				resolve()
			},
			fail: (err) => {
				console.error('高德地图搜索失败:', err)
				uni.showToast({
					title: '搜索失败，请重试',
					icon: 'none'
				})
				loadingStatus.value = 'more'
				reject(err)
			}
		})
	})
}

// 位置验证（备用方案）
function validateCurrentLocation() {
	return new Promise((resolve, reject) => {
		// 如果当前位置有效直接返回
		if (currLocation.value.latitude && currLocation.value.longitude){
			resolve()
			return
		}
		//获取当前位置
		uni.getLocation({
			isHighAccuracy:true,
			type: 'gcj02',
			success: (res) => {
				currLocation.value.latitude = res.latitude
				currLocation.value.longitude = res.longitude
				console.log('获取当前位置', currLocation.value)
				resolve()
			},
			fail: (err) =>{
				console.log('获取当前位置失败', err)
				reject(err)
			}
		})
	})
}

// 选中了位置（当前位置 / 目的地）
function handlerSelect (selectedLocation) {
	if (!selectedLocation.id){
		return
	}
	console.log('选中的位置', selectedLocation)
	
	// 根据页面类型区分选择当前位置 / 目的地
	if(pageType.value === 'current') {
		
		const locationData = {
			location: selectedLocation,
			type:'current'
		}
		console.log('发射当前位置数据:', selectedLocation)
		uni.$emit('selected-new-location', locationData)
		uni.navigateBack()
	} else {
		validateCurrentLocation().then(() => {
			// 高德路径规划计算距离
			const amapKey = '9996b2ae4c2bd5c1caab3861243bb047'
			const origin = `${currLocation.value.longitude},${currLocation.value.latitude}`
			const destination  = `${selectedLocation.location.lng},${selectedLocation.location.lat}`
			const url = `https://restapi.amap.com/v3/direction/driving?key=${amapKey}&origin=${origin}&destination=${destination}&output=JSON`
			uni.request({
				url: url,
				method: 'GET',
				success: (res) => {
					console.log('路径规划结果', res)
					if(res.data && res.data.status === '1' && res.data.route && res.data.route.paths.length > 0){
						const path = res.data.route.paths[0]
						const distance = path.distance // 距离：米
						const duration = path.duration // 时间：秒
						
						console.log(`距离：${distance}, 时间：${duration}`)
						
						//根据距离计算价格
						const disranceKM = Math.ceil(distance / 1000)
						calcPriceByDistance(disranceKM).then(priceRes => {
							const price = priceRes.data.toFixed(1)
							const locationData = {
								value: true,
								location: selectedLocation,//选择的位置
								dist: distance,//距离
								dura: duration,
								price: price,//价钱
								type: 'target'
							}
							
							//通知下单页面为选中目的地
							uni.$emit('selected-new-location', locationData)
					
							// 返回上一页
							uni.navigateBack()
						}).catch(err => {
							console.error('价格计算失败', err)
						})
					}else{
						console.error('路径规划失败:', res.data)
					}
				},
				fail: (err) => {
					console.error('路径规划请求失败:', err)
					uni.hideLoading()
					uni.showToast({
						title: '计算距离失败',
						icon: 'none'
					})
				}
			})
		})
	}
}


// 初始化，当前位置和当前位置（优先使用传递的参数）
onLoad(e => {
	console.log('接收到的参数', e)
	if (e && e.city) {
		// 从传递的完整地址中提取‘市’
		const cityMatch = e.city.match(/(.*?市)/)
		if(cityMatch) {
			region.value = cityMatch[1]
		} else {
			region.value = e.city
		}
		console.log('设置地区为:', region.value)
	}
		
	if (e && e.currLocation) {
		try {
			// 检查currLocation参数是否存在且有效
			if (e.currLocation && e.currLocation !== 'undefined') {
				currLocation.value = JSON.parse(e.currLocation)
				console.log('成功解析当前位置:', currLocation.value)
			} 
		} catch (error) {
			console.error('解析当前位置失败:', error)
		}
	}else {
		// 如果没有传入位置，使用备用方案，自动获取当前位置 
		validateCurrentLocation()
	}
	pageType.value = e.type || 'target'
})

// 触底加载下一页
onReachBottom(() => {
	getNextPage()
})
</script>


<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
.container {
	width: 100vw;
	height: 100vh;
	// overflow-y: scroll;
	background-color: #f8f8f8;
	.head {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		padding: 0 30rpx;
		height: 80rpx;
		background-color: #f8f8f8;
		display: flex;
		align-items: center;
		.left {
			font-size: 30rpx;
			color: #666;
			display: flex;
			align-items: center;
			justify-content: space-between;
			min-width: 130rpx;
			padding-right: 20rpx;
			border-right: 1rpx solid #ccc;
		}
		.right {
			flex: 1;
			padding-left: 20rpx;
		}
	}
	.head-fill {
		height: 80rpx;
	}
	.content {
		background-color: #f8f8f8;
		overflow-y: scroll;
		padding: 20rpx, 30rpx, 30rpx, 30rpx;
		width: 100%;
		.box{
			width: 100%;
			background-color: #fff;
			border-radius: 20rpx;
			.box-head {
				padding: 20rpx 30rpx;
				font-weight: 600;
				font-size: 28rpx;
				border-bottom: 1rpx solid #eee;
			}
			.selectable-location-list{
				padding: 0 30rpx;
				display: block;
				.blank{
					text-align: center;
					padding: 40rpx 0;
					font-size: 22rpx;
					color: #aaa;
				}
				.loading-container {
					text-align: center;
					padding: 20rpx;
					font-size: 22rpx;
				}
				.selectable-location{
					padding: 20rpx 0;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 1rpx solid #eee;
					&:last-child {
						border-bottom: none;
					}
					.left {
						padding: 0 30rpx 0 10rpx;
					}
					.right {
						flex: 1;
						.name{
							font-size: 28rpx;
							font-weight: 600;
						}
						.stress{
							font-size: 21rpx;
							color: #999;
							margin-top: 10rpx;
						}
					}
				}
			}
		}
	}
}
:deep(.uni-load-more__text){
	font-size: 24rpx;
}
</style>